
/**
 * ...
 * @author HTML5
 */

function Sprite()
{
}

Sprite.prototype.uv					= [0, 0, 1, 1];
Sprite.prototype.x 					= 0;
Sprite.prototype.y 					= 0;
Sprite.prototype.z 					= 0;
Sprite.prototype.width 				= 0;
Sprite.prototype.height 			= 0;
Sprite.prototype.alpha 				= 1;
Sprite.prototype.textureId 			= 0;
Sprite.prototype.name 				= "";
Sprite.prototype.displayList 		= null;
Sprite.prototype.transformGroup		= null;
Sprite.prototype.mask				= null;
Sprite.prototype._transformData		= [1,0,0,1,0,0];

Sprite._canvas						= document.createElement("canvas");



Sprite.prototype.drawMask = function( p_texture, p_context )
{
	var canvas = Sprite._canvas;
	var ctx =  canvas.getContext("2d");
	
	var sx = this.uv[0] * p_texture.data.width;
	var sy = this.uv[1] * p_texture.data.height;
	var sw = this.uv[2] * p_texture.data.width;
	var sh = this.uv[3] * p_texture.data.height;
	
	sw -= sx;
	sh -= sy;
	
	
	canvas.width = this.width;
	canvas.height = this.height;
	
	ctx.drawImage( 		this.mask, 
						0, 
						0,
						this.width, 
						this.height	);
						
	
	
	ctx.globalCompositeOperation = "source-in";
	
	if( p_texture.type == Texture2D.COLOR_TEXTURE )
	{
		ctx.fillStyle = p_texture.color;
		ctx.fillRect( this.x , this.y , this.width, this.height );
	}
	else
	{
		ctx.drawImage( 	p_texture.data, 
						sx, 
						sy, 
						sw, 
						sh, 
						0, 
						0, 
						this.width, 
						this.height	);
	}
	
	
	p_context.drawImage( canvas, this.x, this.y, this.width, this.height );
							
};

Sprite.prototype.render = function( p_context )
{

	
	var isAlpha 	= ( this.alpha != 1 );
	var texture		= TextureManager.getInstance().getTextureById(this.textureId);
	var maskCtx		= null;
	
	if( texture == undefined || texture == null )
	{
		return;
	}
	
	var sx = this.uv[0] * texture.data.width;
	var sy = this.uv[1] * texture.data.height;
	var sw = this.uv[2] * texture.data.width;
	var sh = this.uv[3] * texture.data.height;
	
	sw -= sx;
	sh -= sy;
	
	p_context.save();
		
	if( isAlpha )
	{
		p_context.globalAlpha = this.alpha;
	}
	
	
	if( this.transformGroup != null )
	{
		this._transformData = this.transformGroup.transformData;
	}
	
	p_context.setTransform( 
					this._transformData[0],
					this._transformData[1],
					this._transformData[2],
					this._transformData[3],
					this._transformData[4],
					this._transformData[5] );
	
					
					
	if( this.mask != null )
	{
		this.drawMask( texture, p_context );
	}
	else
	{		
		if( texture.type == Texture2D.COLOR_TEXTURE )
		{
			p_context.fillStyle = texture.color;
			p_context.fillRect( this.x , this.y , this.width, this.height );
		}
		else
		{
			p_context.drawImage( 	texture.data, 
									sx, 
									sy, 
									sw, 
									sh, 
									this.x, 
									this.y, 
									this.width, 
									this.height	);
		}
	}
						
	p_context.restore();
};